<template>
  <div class="dialog">
    <el-dialog :title="'物料记录' + titleText" :visible.sync="showDialog" width="70%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <!-- 表单 -->
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="投入鱼塘:" prop="fishPondId" class="w50p">
          <!-- king -->
          <el-select v-model="formData.fishPondId" filterable clearable @change="selectPond">
            <el-option v-for="(item, index) in pondList" :key="index" :label="item.pondName" :value="item.fishPondId" />
          </el-select>
        </el-form-item>

        <el-form-item label="投入批次:" prop="productionBatchId" class="w50p">
          <el-select v-model="formData.productionBatchId" :disabled="!formData.fishPondId" filterable clearable
            no-data-text="请先选择鱼塘" @change="batchChange">
            <el-option v-for="(item, index) in batchList" :key="index" :disabled="item.status == 'COMPLETED'"
              :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId" />
          </el-select>
        </el-form-item>

        <el-form-item label="物料投入人:" prop="staffName" class="w50p">
          <el-select v-model="formData.staffName" filterable clearable>
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffName" />
          </el-select>
        </el-form-item>
        <el-form-item label="投塘日期：" class="w50p" prop="inputDate">
          <!--  value-format="yyyy-MM-dd HH:mm:ss" -->
          <el-date-picker v-model="formData.inputDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期" clearable :picker-options="pickerOptions" />
        </el-form-item>
        <el-form-item label="投入说明：" class="w100p">
          <el-input type="textarea" v-model="formData.explain" clearable placeholder="请输入投入说明" maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="备注：" class="w100p">
          <el-input type="textarea" v-model="formData.remark" clearable placeholder="请输入备注" maxlength="100"
            show-word-limit>
          </el-input>
        </el-form-item>
        <template v-if="titleText == '添加'">
          <div style="width: 100%;  display: flex;" v-for="materialInfo, index in formData.materialMap" :key="index">
            <el-form-item label="物料名称:" :prop="'materialMap.' + index + '.materialId'" :rules="rules.materialId">
              <el-select v-model="materialInfo.materialId" filterable clearable @change="materialChange($event)">
                <el-option v-show="item.materialTypeNo !== 'FEED'" v-for="(item, index) in materialList" :key="index"
                  :label="item.name" :value="item.materialId" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料投入量：" :prop="'materialMap.' + index + '.amount'" :rules="rules.amount">
              <el-input type="number" :disabled="!materialInfo.materialId" v-model.number="materialInfo.amount" clearable
                placeholder="请输入物料投入量：" @change="() => {
                  materialInfo.num = materialInfo.amount / materialObj[materialInfo.materialId].ratioNum
                  $set(formData.materialMap, index, {
                    materialId: materialInfo.materialId,
                    num: materialInfo.num,
                    amount: materialInfo.amount
                  })
                }">
              </el-input>
              <div style="width: 100px; height: 36px;background: #ededed;text-align: center;border: 1px solid #dcdcdc;
                  transform: translate(-4px);box-sizing: border-box;">
                {{ materialInfo.materialId ? materialObj[materialInfo.materialId].unit : '' }}</div>
            </el-form-item>
            <el-form-item label="物料数量：" :prop="'materialMap.' + index + '.num'" :rules="rules.num">
              <el-input type="number" :disabled="!materialInfo.materialId" v-model.number="materialInfo.num" clearable
                placeholder="请输入数量" @change="() => {
                  materialInfo.amount = materialInfo.num * materialObj[materialInfo.materialId].ratioNum
                  $set(formData.materialMap, index, {
                    materialId: materialInfo.materialId,
                    num: materialInfo.num,
                    amount: materialInfo.amount
                  })
                }">
              </el-input>
              <div style="width: 100px; height: 36px;background: #ededed;text-align: center;border: 1px solid #dcdcdc;
                  transform: translate(-4px);box-sizing: border-box;">
                {{ materialInfo.materialId ? materialObj[materialInfo.materialId].aUnit : '' }}</div>
            </el-form-item>
            <!-- 增加/减少-按钮 -->
            <div style="font-size: 26px;color: #999999;line-height: 36px;  cursor: pointer;width:90px">
              <i class="el-icon-remove-outline" style="margin-left: 10px;" @click="removeData(materialInfo, index)"></i>
              <i class="el-icon-circle-plus-outline" style="margin-left: 10px;" @click="plusData(materialInfo, index)"
                v-show="formData.materialMap.length == index + 1"></i>
            </div>
          </div>
        </template>
        <template v-if="titleText == '修改'">
          <el-form-item label="物料名称:" prop="materialId">
            <el-select v-model="formData.materialId" filterable clearable @change="materialChange($event)">
              <el-option v-show="item.materialTypeNo !== 'FEED'" v-for="(item, index) in materialList" :key="index"
                :label="item.name" :value="item.materialId" />
            </el-select>
          </el-form-item>
          <el-form-item label="物料投入量：" prop="amount" :rules="rules.amount">
            <el-input type="number" v-model.number="formData.amount" clearable placeholder="请输入物料投入量" @change="() => {
              formData.num = Number(formData.amount) / materialObj[formData.materialId].ratioNum
              $set(formData, 'num', formData.num)
            }">
            </el-input>
            <div style="width: 100px; height: 36px;background: #ededed;text-align: center;border: 1px solid #dcdcdc;
                transform: translate(-4px);box-sizing: border-box;">
              {{ formData.materialId ? materialObj[formData.materialId].unit : '' }}</div>
          </el-form-item>
          <el-form-item label="物料数量：" prop="num" :rules="rules.num">
            <el-input type="number" v-model.number="formData.num" clearable placeholder="请输入数量" @change="() => {
              formData.amount = Number(formData.num) * materialObj[formData.materialId].ratioNum
              $set(formData, 'amount', formData.amount)
            }">
            </el-input>
            <div style="width: 100px; height: 36px;background: #ededed;text-align: center;border: 1px solid #dcdcdc;
                transform: translate(-4px);box-sizing: border-box;">
              {{ formData.materialId ? materialObj[formData.materialId].aUnit : '' }}</div>
          </el-form-item>
        </template>

        <el-form-item label="投入凭证：" class="w50p" prop="fileIdList">
          <EleUploadImage ref="EleUploadImage" multiple :responseFn="handleResponse" :action="baseurl" :headers="headers"
            :isShowSuccessTip="false" :beforeRemove="beforeRemove" :fileSize="5" :fileType="['png', 'jpg', 'jpeg', 'pdf']"
            v-model="images" />
        </el-form-item>

        <el-form-item style="width: 100%;padding-left: 140px;">
          <div style="width: 100%;display: flex;justify-content: start;flex-wrap: wrap;margin-bottom: 10px;">
            <div class="imgItem" v-for="item, index in images" :key="index" @click="delImgItem(index)">
              <iframe style=" width: 150px; height: 150px;" :src="item + '#view=FitH,top'" scrolling="no" frameborder="0"
                width="100%" height="100%"></iframe>
              <!-- <img style="width: 100%;height: 100%;" :src="item" alt=""> -->
              <div class="zhezhao">
                <i class="el-icon-delete"></i>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FishPondApi from "@/api/basic-info-manage/fishPond"
import InputManageApi from "@/api/input-manage";
import BatchMangeApi from "@/api/batch-mange";
import EleUploadImage from "vue-ele-upload-image";
import DocumentApi from "@/api/document"
import { blobToBase64 } from "@/utils/convert";
import { dialogMixin } from "@/utils/dialogMixin";
import store from "@/store";
let maxTime = null
export default {
  name: "",
  components: { EleUploadImage },
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return [];
      }
    },
    materialList: {
      type: [Array],
      default: () => {
        return [];
      }
    }
  },


  created() {
    this.queryFishPond()
    maxTime = null

  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && Number(value) > 99999) {
        } else if (Number(value) && Number(value) > 0 && Number(value) < 99999) {
          callback();
        } else {
          return callback(new Error("请输入大于0的数,小于99999的数！"));
        }
      } else {
        return callback(new Error("请输入大于0的数！"));
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      rules: {
        materialId: [
          {
            required: true,
            message: "请选择物料名称",
            trigger: ["change", "blur"]
          }
        ],
        amount: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: checkInt
          }
        ],
        num: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: checkInt
          }
        ],
        fishPondId: [
          {
            required: true,
            message: "请选择投入鱼塘",
            trigger: ["change", "blur"]
          }
        ],
        productionBatchId: [
          {
            required: true,
            message: "请选择投入批次",
            trigger: ["change", "blur"]
          }
        ],
        staffName: [
          {
            required: true,
            message: "请选择经手人",
            trigger: ["change", "blur"]
          }
        ],
        inputDate: [
          {
            required: true,
            message: "请选择投塘日期",
            trigger: ["change", "blur"]
          }
        ],
      },
      baseurl: this.$baseurl.fileServiceUrl + "base/files/upload",
      headers: {
        token: sessionStorage.getItem("token"),
        homeBaseId: sessionStorage.getItem("homeBaseId"),
      },
      images: [],
      fileIdList: [],
      formData: {},
      pondList: [],
      batchList: [], //批次
      showDialog: this.show,
      batchId: '',
      batchName: '',
      amount: 0,
      imagesMap: {},
      auxiliaryUnitNo: undefined,
      formData: {
        staffId: '',
        staffName: '',
        fishPondId: '',
        explain: '',
        materialMap: [{ materialId: '', amount: '', num: '' }], // 物料名称+物料投入量
      }
    };
  },
  computed: {
    materialObj() {
      return store.state.basicData.material;
    }
  },
  watch: {
    nowChanceStau(v) {
      maxTime = null
      if (v === "add") {
        this.formData = {
          staffId: '',
          staffName: '',
          inputDate: '',
        }
        this.$set(this.formData, 'inputDate', this.getNowTime())
        this.batchList = []
        this.batchName = ''
        this.images = []
        let staffName = sessionStorage.getItem('staffName');
        let staffId = sessionStorage.getItem('staffId');
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData.staffName = userList.length == 0 ? this.staffList[0].staffName : staffName
        this.formData.staffId = userList.length == 0 ? this.staffList[0].staffId : Number(staffId)
        this.$refs['ruleForm'] && this.$refs['ruleForm'].clearValidate()
        this.$set(this.formData, 'materialMap', [{}]);
        this.formData.materialMap.forEach((item) => {
          this.$set(item, 'materialId', '')
          this.$set(item, 'amount', '')
        });
        // this.$nextTick(() => { 
        //   if (sessionStorage.getItem("staffId") == 1) {
        //     this.formData.staffName = this.staffList[0].staffName
        //     this.formData.staffId = this.staffList[0].staffId
        //   } else {
        //     this.formData.staffName = sessionStorage.getItem("staffName")
        //     this.formData.staffId = Number(sessionStorage.getItem("staffId"))
        //   }
        //   this.$refs['ruleForm'].clearValidate()
        // })

      }
      if (v === "edit") {
        this.formData = this.editObject;
        this.formData.staffName = this.formData.staffName && this.formData.staffName !== 'null' ? this.formData.staffName : ''
        this.$set(this.formData, 'num', Number(this.formData.amount) / this.materialObj[this.formData.materialId].ratioNum)
        this.images = []
        this.queryFileId(this.formData.fileIdList)
        let king = JSON.parse(sessionStorage.getItem('kingfishPondId'))
        this.batchName = king.batchName
        this.queryBatch(king.fishPondId)
      }
    },
    show(v) {
      // this.showDialog = v;
      setTimeout(() => {
        this.showDialog = v;
        this.$refs['ruleForm'] && this.$refs['ruleForm'].clearValidate()
      }, 1)
    }
  },
  methods: {
    // 添加物料名称/数量行
    plusData(info, index) {
      this.$set(this.formData.materialMap, index + 1, {
        materialId: '', amount: ''
      })
    },
    // 减少物料名称/数量行
    removeData(info, index) {
      if (this.formData.materialMap.length > 1) {
        this.formData.materialMap.splice(index, 1)
      } else {
        this.$message.info('不可以删除哦，至少一条物料记录！')
      }
    },
    delImgItem(index) {
      this.images.splice(index, 1)
      this.fileIdList.splice(index, 1)
    },
    batchChange(e) {
      maxTime = ''
      this.formData.inputDate = new Date()
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          maxTime = new Date(item.buildDateTime)
          // this.$refs['ruleForm'].clearValidate('productionBatchId') 
          this.$nextTick(() => { this.$refs['ruleForm'].clearValidate('productionBatchId') })
          //this.formData.inputDate = this.formatDateTimeMHS(maxTime) 
        }
      })
    },
    getNowFormatDate() {
      let date = new Date(),
        seperator1 = '-', //格式分隔符
        year = date.getFullYear(), //获取完整的年份(4位)
        month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
        strDate = date.getDate() // 获取当前日(1-31)
      H = date.getHours() // 获取时
      M = date.getMinutes()// 获取分
      S = date.getSeconds()// 获取秒
      if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
      if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0
      // if (H >= 0 && H <= 9) H = '0' + H
      // if (M >= 0 && M <= 9) M = '0' + M // 如果日是个位数，在前面补0
      // if (S >= 0 && S <= 9) S = '0' + S // 如果日是个位数，在前面补0
      let currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    materialChange(e) {
      console.log(e);
      this.materialList.find(item => {
        if (item.materialId === e) {
          if (!item.basicUnitName) {
            item.basicUnitName = ''
          }
          if (!item.auxiliaryUnitName) {
            item.auxiliaryUnitName = ''
          }
          // this.auxiliaryUnitNo = `${item.basicUnitName} ${item.basicUnitName && item.auxiliaryUnitName ? '/' : ''}${item.auxiliaryUnitName}`
          this.auxiliaryUnitNo = `${item.basicUnitName}`
          return true
        }
      })
    },
    // king start
    //查询可选鱼塘
    async queryFishPond() {
      let res = await FishPondApi.queryByCondition()
      this.pondList = res.data;
    },
    // 查詢批次
    async queryBatch(e) {
      let res = await BatchMangeApi.queryBatchByPondIdUnComplete({ pondId: e })
      this.batchList = res.data
    },
    // 選擇魚塘
    selectPond(e) {
      this.batchList = []
      this.batchName = ''
      this.$set(this.formData, 'productionBatchId', null)
      if (e) {
        this.queryBatch(e)
      }
    },
    // 投入凭证
    queryFileId(fileIdList) {
      if (fileIdList !== null && fileIdList.length > 0) {
        this.fileIdList = fileIdList
        fileIdList.forEach(async item => {
          await DocumentApi.fileDownload({ fileId: item }).then(res => {
            console.log(res)
            blobToBase64(res.data).then(res2 => {
              this.images.push(res2)
              this.imagesMap[res2] = item
              console.log(this.images)
            })
          })
        })
        this.showPictureDialog = true;
      } else this.fileIdList = []
    },
    beforeRemove(file) {
      const index = this.fileIdList.findIndex(val => { return val == this.imagesMap[file] })
      this.fileIdList.splice(index, 1)
    },
    selectBatch(e) {
      if (e != '') {
        let testId = this.batchList.filter((item) => {
          return item.mnecode == e
        })
        this.formData.productionBatchId = testId[0].productionBatchId
      } else {
        this.formData.productionBatchId = -999
      }
    },
    // king end
    handleResponse(res, file, fileList) {
      if (res.success) {
        this.fileIdList.push(res.data);
        // this.images = []
        // this.queryFileId(this.fileIdList)
        this.$message.success("上传成功");
        return file.url;
      } else if (res.success === false && res.errCode === 200) {
        this.$message.error(res.message);
      } else {
        this.$message.error("上传失败，请稍后再试");
      }
    },
    // 保存
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            this.formData.fileIdList = this.fileIdList;
            InputManageApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.fileIdList = this.fileIdList;
            // 物料名称+投入数量
            let maoInfo = {}
            this.formData.materialMap.forEach(info => {
              maoInfo[info.materialId] = info.amount
            })
            InputManageApi.addList({ ...this.formData, ...{ materialMap: maoInfo } }).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.batchList = []
                this.batchName = ''
                this.close();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
      if (this.nowChanceStau === "add") {
        this.batchList = []
        this.batchName = ''
      }
    },
    cancel() {
      this.fileIdList = []
      this.$emit("cancelDialog");
      if (this.nowChanceStau === "add") {
        this.batchList = []
        this.batchName = ''
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list__item {
  display: none;
}

.imgItem {
  width: 150px;
  height: 150px;
  margin-right: 10px;
  background: #cecece;
  overflow: hidden;
  position: relative;

  .zhezhao {
    position: absolute;
    width: 100%;
    height: 100%;
    background: #3333333b;
    top: 0;
    left: 0;
    display: none;

    .el-icon-delete {
      font-size: 20px;
      color: #333;
      line-height: 150px;
      padding-left: 60px;
      cursor: pointer;
    }
  }
}

.imgItem:hover .zhezhao {
  display: block;
}
</style>
